import fs from "fs";
import pLimit from "p-limit";
import path from "path";
import cliProgress from "cli-progress";
import { axiosInstance as axios, fileUtils, getConfig } from "./axios.js";
import { sleep } from "../../utils/canvasUtils.js";
import { img } from "../canvas-icon/types.js";

const headers = {
  accept: "application/json, text/plain, */*",
  "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
  appid: "",
  "cache-control": "no-cache",
  device: "web",
  distinct_id: "mk_dst_1733466385632dge3cl33maf1nfbjbk01f132g1cclaem",
  distinctid: "mk_dst_1733466385632dge3cl33maf1nfbjbk01f132g1cclaem",
  pragma: "no-cache",
  priority: "u=1, i",
  "sec-ch-ua":
    '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": '"Windows"',
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-site",
  token:
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtYWthNjA0ODUwNDA1IiwidWlkIjo2MDQ4NTA0MDUsImFwcGlkIjoibWFrYSIsInVzZXJuYW1lIjoib1RqMUFzOHp5RENYcmgza2RtVFotSVRLdE5uOCIsImlhdCI6MTczMzQ2NjQ1NiwiZXhwIjoxNzM2MDU4NDU2fQ.ufwjjC1uP96g9ro7hwsF1pY42X6ajYTtCc1SO6wVasE",
  uid: "604850405",
  Referer:
    "https://www.maka.im/s-muban/%E5%86%AC%E8%87%B3.html?parent_page_type=site_search_total&ref_page_id=%E5%86%AC%E8%87%B3",
  "Referrer-Policy": "no-referrer-when-downgrade",
};

async function main() {
  const { lastPageMap, lastTokenMap } = fileUtils.config;
  try {
    for (const node in lastTokenMap) {
      const end = (lastPageMap[node] as unknown as number) || 0;
      const { total_cnt } = await getImageUrls(1, node);
      const total = total_cnt / 100;
      for (let i = 1; i <= total; i++) {
        if (i > end) {
          break;
        }
        await mark(i, node);
      }
    }
  } catch (e) {
    fileUtils.logError(e);
  }
}

// ===============【1】请求获取到pdf链接 ===========================
async function getImageUrls(p: number, tip: string) {
  const baseUrl =
    "https://apig.maka.im/ccloud/search/v1/search?cli_rev=1.0&platform=web&n=100";
  const commonQueryParams =
    "&oq=&orderby=&free=&category=&spec=&style=&scene=&industry=&ex_category=&color=&channel=&u=604850405";
  const q = encodeURIComponent(tip);
  const url = baseUrl + `&p=${p}&q=${q}` + commonQueryParams;

  try {
    const response = await axios.get(url, {
      headers,
    });

    const data = response.data;
    const result = data.result;
    const { total_cnt, template_list } = result;

    const imgList: img[] = template_list.map((item: any) => {
      const { preview_image_url, template } = item;
      const url = preview_image_url;
      const token = template;
      return { url, token };
    });

    return { total_cnt, imgList };
  } catch (error) {
    console.error("Error fetching data:", error);
    throw error;
  }
}

// 传入uid
async function getWorks_id(template_id: string) {
  const url = "https://apiv5.maka.im/works/index/add";
  const headers = {
    accept: "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    appid: "",
    "cache-control": "no-cache",
    "content-type": "application/json",
    device: "web",
    distinct_id: "mk_dst_1733466385632dge3cl33maf1nfbjbk01f132g1cclaem",
    distinctid: "mk_dst_1733466385632dge3cl33maf1nfbjbk01f132g1cclaem",
    pragma: "no-cache",
    "sec-ch-ua":
      '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    token:
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtYWthNjA0ODUwNDA1IiwidWlkIjo2MDQ4NTA0MDUsImFwcGlkIjoibWFrYSIsInVzZXJuYW1lIjoib1RqMUFzOHp5RENYcmgza2RtVFotSVRLdE5uOCIsImlhdCI6MTczMzQ2NjQ1NiwiZXhwIjoxNzM2MDU4NDU2fQ.ufwjjC1uP96g9ro7hwsF1pY42X6ajYTtCc1SO6wVasE",
    uid: "604850405",
    Referer: `https://www.maka.im/template/${template_id}.html?parent_page_type=site_search_total&page_inst_id=&ref_page_id=%E5%86%AC%E8%87%B3&hotword_floor_word_btn=`,
    "Referrer-Policy": "no-referrer-when-downgrade",
  };
  const body = {
    template_id,
    from: "editor7",
    spec_id: 330,
  };

  try {
    const response = await axios.post(url, body, { headers });
    const data = response.data.data;
    const { works_id, uid, title } = data;
    return { works_id, uid, title };
  } catch (error) {
    console.error("There was an error making the request:", error);
    throw error;
  }
}

async function mark(page: number, node: string) {
  const { imgList } = await getImageUrls(page, node);
  const tokens = imgList.map((item) => item.token);
  for (const token of tokens) {
    const { works_id } = await getWorks_id(token);
    const JsonUrl = await fetchData(works_id);
    console.log(JsonUrl);
  }
}

async function fetchData(works_id: string) {
  try {
    const dataUrl = `https://maka-frontend-fe.maka.im/works-store/v7/works/604850405/${works_id}`;
    const response = await axios.get(dataUrl, {
      headers: {
        accept: "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "cache-control": "no-cache",
        device: "web",
        pragma: "no-cache",
        priority: "u=1, i",
        "sec-ch-ua":
          '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        token:
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtYWthNjA0ODUwNDA1IiwidWlkIjo2MDQ4NTA0MDUsImFwcGlkIjoibWFrYSIsInVzZXJuYW1lIjoib1RqMUFzOHp5RENYcmgza2RtVFotSVRLdE5uOCIsImlhdCI6MTczMzQ2NjQ1NiwiZXhwIjoxNzM2MDU4NDU2fQ.ufwjjC1uP96g9ro7hwsF1pY42X6ajYTtCc1SO6wVasE",
        uid: "604850405",
        Referer: "https://www.maka.im/",
        "Referrer-Policy": "strict-origin-when-cross-origin",
      },
    });
    // 成功返回处理逻辑
    const work_data = response.data.detail;
    const { worksUrl } = work_data;
    return worksUrl;
  } catch (error) {
    // 错误处理逻辑
    console.error("Error fetching data:", error);
  }
}

// ===================== 【2】下载图片到本地 =====================
//纯函数： 下载文件，并重试三次
async function downloadImgWithRetry(
  imgUrl: string,
  filePath: string,
  retries = 3
) {
  // 如果文件已经存在，则直接返回
  if (fs.existsSync(filePath)) {
    return;
  }
  try {
    const res = await axios.get(imgUrl, {
      responseType: "arraybuffer",
    });
    fs.writeFileSync(filePath, Buffer.from(res.data));
  } catch (error) {
    if (retries > 0) {
      console.log(`⚠️ 图片下载失败，重试中...`);
      sleep(1000, 1000);
      return downloadImgWithRetry(imgUrl, filePath, retries - 1);
    } else {
      fileUtils.logError(error);
    }
  }
}

//下载函数的封装
async function downloadImgs(keyword: string, imgUrls: img[]) {
  console.log(`🔥 开始下载 ${imgUrls.length} 张图片`);
  const dir = path.resolve(fileUtils.outDirPath, keyword);
  fs.mkdirSync(dir, { recursive: true }); //确保目录存在
  const limit = pLimit(fileUtils.config.concurrency); // 限制下载并发

  // 初始化进度条
  const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.rect);
  progressBar.start(imgUrls.length, 0);
  const promises = imgUrls.map(async (imgUrl) => {
    //文件名处理
    const filePath = await fileNameHandle(imgUrl.token, dir);
    return limit(async () => {
      await downloadImgWithRetry(imgUrl.url, filePath);
      progressBar.increment(); // 更新进度条
    });
  });

  await Promise.all(promises);
  progressBar.stop(); // 停止进度条
}

//====================【3】参数处理===========================
//文件名处理函数
const fileNameHandle = async (imgUrl: string, dir: string): Promise<string> => {
  const fileName = `${imgUrl}.jpg`;
  const filePath = `${dir}/${fileName}`;
  return filePath;
};

//配置参数处理函数
const lastTokenHandle = async (path: string, index: number) => {
  const config = fileUtils.config;
  const { lastPageMap = {} } = config;

  // 确保 lastPageMap 和 path 对应的对象存在
  if (!lastPageMap[path]) {
    lastPageMap[path] = {};
  }

  lastPageMap[path].page = index;

  fileUtils.writeConfig({ ...config, lastPageMap });
};

// 初始配置函数，简化chunfig的配置
const initWriteConfig = async (list: any, isupdate: boolean = false) => {
  const config = fileUtils.config;
  const { lastPageMap = {}, lastTokenMap = [] } = config;

  for (const [key, end] of list) {
    // 默认 end 值为 3，如果未提供则使用这个默认值
    const finalEnd = end ?? 3;

    // 如果 lastPageMap 中不存在该 key，则初始化
    if (!lastPageMap.hasOwnProperty(key)) {
      lastTokenMap.push(key);
      lastPageMap[key] = {
        page: 0,
        end: finalEnd,
      };
    } else {
      // 如果存在该 key，则更新正在的字段
      lastPageMap[key].end = finalEnd;
    }
  }
  if (isupdate) {
    // 更新配置，并写入
    fileUtils.writeConfig({ ...config, lastPageMap, lastTokenMap });
  } else {
    fileUtils.writeConfig({ lastPageMap, lastTokenMap });
  }
};
